package com.jinbei.task;

import com.alibaba.fastjson.JSONObject;
import com.jinbei.cache.EhCacheService;
import com.jinbei.common.Contants.Contants;
import com.jinbei.common.base.BaseRedisService;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author zflu
 * 系统启动时执行查询redis的持久化缓存，注入到 ehcache
 * 2018年7月9日13:46:00
 * Created by lucky on 2018/7/9.
 */
@Component
@Order(1)
public class CacheRunner implements CommandLineRunner {

    private Logger logger = LoggerFactory.getLogger(CacheRunner.class);

    @Autowired
    private BaseRedisService redisService;
    @Autowired
    private EhCacheService cacheService;

    @Override
    public void run(String... strings) throws Exception {
        logger.info("-------init ehCache start-------");
        try {
            Map<Object, Object> map = redisService.hmget(Contants.COURSE_KEY);
            List<Element> list = new ArrayList<>();
            if(map != null){
                Iterator<Map.Entry<Object, Object>> it = map.entrySet().iterator();
                while (it.hasNext()){
                    Map.Entry<Object, Object> next = it.next();
                    Object value = next.getValue();
                    String data = null;
                    if(value != null){
                        data = JSONObject.parseObject(value.toString()).getString(Contants.DATA);
                    }
                    Element element = new Element(next.getKey(),data);
                    list.add(element);
                }
            }
            cacheService.addCacheList(list);
        }catch (Exception e){
            logger.error("初始化 ehCache 失败 error: {}",e);
        }
        logger.info("-------init ehCache end-------");
    }
}
